import Taro from "@tarojs/taro";
import { serverHost, getToken, navigateTo, showToast } from "./common";


/*function parseJSON(response) {
  return response.json();
}*/

function checkStatus(response, callback) {
  if (response.statusCode == 401) {
    const error = new Error("clear");
    error["response"] = response;
    error["callback"] = callback;
    throw error;
  }
  return response;
}

function checkSuccess(data, callback) {
  if (data.success === true) {
    Taro.hideLoading()
    return data.result;
  } else {
    const error = new Error(data.error.message);
    error["response"] = data.error.details;
    error["callback"] = callback;
    throw error;
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request({ url, options },   callback?, isLoading = true) {
  options.headers = Object.assign({}, options.headers, getToken());
  const { body, headers, method } = options;
  if(!headers.hasOwnProperty('Content-Type')) { headers['Content-Type'] = 'application/json' }
  if (isLoading) {
    Taro.showLoading({
      title: '加载中...',
      mask: true
    });
  }
  return Taro.request({
    url: serverHost + url,
    data: body,
    header: headers,
    method: method,
    // mode: "no-cors"
  })
    .then(res => {
      return checkStatus(res, callback)
    })
    .then(res => res.data)
    .then(data => checkSuccess(data, callback))
    .catch(err => {
      console.log(err)
      Taro.hideLoading()
      if (err.message == "clear") {
        setTimeout(() => {
          navigateTo("/pages/login/login")
        }, 1000);
        throw err;
      }
      else {
        showToast(err.message);
        throw err;
      }
    });
}


/*
import Taro from "@tarojs/taro";
import {getToken, navigateTo, serverHost} from './common'

export default function request({url, options}) {

  options.headers = Object.assign({}, options.headers, getToken());
  const { body, headers, method } = options;
  console.log(headers)
  console.log(options)
  Taro.showLoading({title: '加载中...', mask: true})
  console.log(headers)
  return Taro.request({
    url: serverHost + url,
    data: body,
    header: headers,
    method: method,
    mode: "no-cors"
  }).then(response => {
    console.log(response)
    return
    return checkCode(response)
  }).then(data => {
    return checkData(data)
  })
    .catch(err => {
      console.log(err)
      Taro.hideLoading()
      if (err.name === 'unAuthorization') {
        navigateTo('/pages/login/login');
        return;
      }
      throw err
    })
}

const checkCode = (res) => {
  Taro.hideLoading()
  if (res.statusCode === 401) {
    let errCode = new Error()
    errCode.name = 'unAuthorization'
    errCode.message = '无权限访问或需要登录'
    throw errCode
  }
  if (res.statusCode === 200) {
    return res.data
  }
  return res
}

const checkData = (data) => {
  if (!data.success) {
    let errData = new Error()
    errData.name = 'system error'
    errData.message = data.error
    throw errData
  }
  return data.result
}
*/
